var util = require('./util.js');
var app = getApp();

var HOST;

/**
 * 仿ajaxGet的方法
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _Get(url, data, success, fail) {
  _request('get', url, data, success, fail);
}

/**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _Post(url, data, success, fail) {
  _request('post', url, data, success, fail);
}

function _request(method, url, data, success, fail) {
  var userSid = app.getUserSid();
  var alias = app.getAlias();
  var requestObj;
  var header = {};

  HOST = app.getHost();

  method = (method || 'get').toLowerCase();
  url += '?alias=' + alias;
  data = data || {};
  data.userSid = userSid;

  if (method == 'post') {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  } else { //get
    let params = '';

    Object.keys(data).forEach(function (key) {
      var val = data[key];

      if (val instanceof Array) {
        val.forEach(function (v) {
          params += '&' + key + '[]=' + v;
        });
      } else {
        params += '&' + key + '=' + val;
      }
    });
    url += params;
  }

  requestObj = {
    url: HOST + url,
    header: header,
    method: method,
    success: function (res) {
      var data = res.data;

      if (data.code == 0) {
        typeof success == "function" && success(data);
      } else {
        if (typeof fail == "function") {
          return fail(data);
        }
        if (data.msg) {
          util.alert(data.msg);
        }
        // if (data.code == 107) {
        //   wx.navigateTo({
        //     url: '/pages/login/login'
        //   });
        // }
      }
    },
    fail: function (res) {
      typeof fail == "function" && fail(res);
    }
  };

  if (method == 'post') {
    requestObj.data = data;
  }

  wx.request(requestObj);
}

module.exports = {
  P: _Post,
  G: _Get
}